using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace GameServer.Timer
{
    /// <summary>
    /// 计时器
    /// </summary>
    public class TimeManager
    {
        /// <summary>
        /// 这个字典存储id和Model的映射
        /// </summary>
        private ConcurrentDictionary<int, TimerModel> idModelDict = new ConcurrentDictionary<int, TimerModel>();

        /// <summary>
        /// 要移除的任务id列表
        /// </summary>
        private List<int> removeList = new List<int>();

        private static TimeManager instance = null;
        public static TimeManager Instance
        {
            get
            {
                lock (instance)
                {
                    if (instance == null)
                    {
                        instance = new TimeManager();
                    }
                    return instance;
                }
            }
        }
        /// <summary>
        /// 实现定时器的主要功能就是系统提供的Timer类
        /// </summary>
        System.Timers.Timer timer;
        /// <summary>
        /// 用来表示id
        /// </summary>
        private Concurrent.ConcurrentInt id = new Concurrent.ConcurrentInt(-1);

        public TimeManager()
        {
            timer = new System.Timers.Timer(10);
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (removeList)
            {
                TimerModel model = null;
                foreach (var id in removeList)
                {
                    idModelDict.TryRemove(id, out model);
                }
            }
       
            foreach(var item in idModelDict.Values)
            {
                if(item.Time <= DateTime.Now.Ticks)
                    item.Run();
            }
        }

        /// <summary>
        /// 定时任务, 触发时间
        /// </summary>
        public void AddTimerEvent(DateTime datetime, TimeDelegate timeDelegate)
        {
            long delayTime = datetime.Ticks - DateTime.Now.Ticks;
            if(delayTime < 0)
            {
                return;
            }
            AddTimerEvent(delayTime, timeDelegate);
        }

        /// <summary>
        /// 定时任务, 延迟执行
        /// </summary>
        public void AddTimerEvent(long delayTime, TimeDelegate timeDelegate)
        {
            TimerModel model = new TimerModel(id.Add_Get(), DateTime.Now.Ticks + delayTime, timeDelegate);
            idModelDict.TryAdd(model.Id, model);


        }
    }
}
